package com.heima.behavior.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
@Transactional
@Slf4j
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    public ResponseResult likes(LikesBehaviorDto dto) {
        //1.判断参数
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = ApThreadLocalUtils.getUser();
        Integer userId = null;
        if(apUser.getId()!=null && apUser.getId()>0){
            userId = apUser.getId();
        }

        //2.查询行为实体判断是否存在
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdAndEquipmentId(userId, dto.getEquipmentId());
        if(apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "行为实体不存在");
        }

        //3.查询点赞行为数据
        ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApLikesBehavior::getType, dto.getType()));

        //4.判断如果点赞行为数据不存在，就新增
        if(apLikesBehavior==null){
            if(dto.getOperation().equals(ApLikesBehavior.Operation.CANCEL.getCode())){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "数据不存在，不允许取消点赞");
            }

            apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setEntryId(apBehaviorEntry.getId());//行为实体ID
            apLikesBehavior.setArticleId(dto.getArticleId());//文章ID
            apLikesBehavior.setType(dto.getType()); //文章、动态、评论
            apLikesBehavior.setOperation(dto.getOperation()); //0-点赞 1-取消点赞
            apLikesBehavior.setCreatedTime(new Date());
            save(apLikesBehavior);

        } else {
            //5.判断如果点赞行为数据存在，就更新

            //情况1：数据存在且状态为点赞，此时用户操作点赞，那么判定为重复点赞
            if(apLikesBehavior.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())
                && dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不要重复点赞");
            }

            //情况2：数据存在且状态为取消点赞，此时用户操作取消点赞，那么判定为重复取消点赞
            if(apLikesBehavior.getOperation().equals(ApLikesBehavior.Operation.CANCEL.getCode())
                    && dto.getOperation().equals(ApLikesBehavior.Operation.CANCEL.getCode())){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "不要重复取消点赞");
            }

            ApLikesBehavior apLikesBehaviorDB = new ApLikesBehavior();
            apLikesBehaviorDB.setId(apLikesBehavior.getId());
            apLikesBehaviorDB.setOperation(dto.getOperation());
            updateById(apLikesBehaviorDB);
        }


        //如果当前操作是点赞，那么就将此次点赞数据生产到kakfa中
        if(dto.getOperation().equals(ApLikesBehavior.Operation.LIKE.getCode())){

            UpdateArticleMess updateArticleMess = new UpdateArticleMess();
            updateArticleMess.setArticleId(dto.getArticleId()); //文章ID
            updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES); //点赞类型

            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(updateArticleMess));
        }


        //6.响应数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
